package sostats.core.base;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import sostats.core.metadata.Table;

import com.google.common.base.Function;
import com.google.common.collect.Lists;

public class TableNode extends Node implements Table{
	List<SummaryLeaf> summaries = new ArrayList<SummaryLeaf>();
	List<CategoryLeaf> categories = new ArrayList<CategoryLeaf>();
	HashMap<String,Joint> map = new HashMap<String, Joint>();
	public TableNode(String name) {
		super(name);
	}
	public void addCategoryLeaf(String name, String description){
		CategoryLeaf leaf = new CategoryLeaf(name, description);
		categories.add(leaf);
	}
	public void addSummaryLeaf(String name, String description){
		SummaryLeaf leaf = new SummaryLeaf(name, description);
		summaries.add(leaf);
	}
	@Override
	public String getTableName() {
		return super.getName();
	}
	@Override
	public Joint getJoint(Path path) {
		return map.get(path.endValue());
	}
	@Override
	public List<Table> getJointTables() {
		return Lists.transform(new ArrayList<Joint>(map.values()), new Function<Joint,Table>(){
			@Override
			public Table apply(Joint input) {
				return input.getTarget();
			}
		});
	}
	public void addJoint(String tableName, String fk, String pk) {
		TableNode node = new TableNode(tableName);
		map.put(tableName,new DefaultJoint(node,fk,pk,this));
	}
	private class DefaultJoint implements Joint{
		private TableNode target;
		private String pk;
		private String fk;
		private TableNode joined;
		public DefaultJoint(TableNode target, String fk, String pk,TableNode joined){
			this.fk = fk;
			this.pk = pk;
			this.target = target;
		}
		@Override
		public Table getTarget() {
			return target;
		}
		
		@Override
		public String getPk() {
			return pk;
		}
		@Override
		public String getFk() {
			return fk;
		}
		@Override
		public Table getJoinedTable() {
			return joined;
		}
	}
	
}
